import { ChatGPTAPI } from "chatgpt";
import { defer } from "utils-lib-js";
export class ChatGPTApi {
  constructor(...opts) {
    if (!!!this.chatApi) this.chatApi = new ChatGPTAPI(...opts);
    return this;
  }
  info = null;
  // {
  //   role: 'assistant',
  //   id: 'cmpl-6gxxxxxxxxxxxxxsJ5',
  //   parentMessageId: 'b62b46xxxxxxxxxxxxxxxxxxxxx8b16f6',
  //   conversationId: '3a97ec0xxxxxxxxxxxxxxxxx479',
  //   text: "hello"
  // }
  // 直接发送，每次都是新消息
  send({ msg, opts }) {
    const { promise, resolve, reject } = defer();
    this.chatApi
      .sendMessage(msg, opts)
      .catch(reject)
      .then((res) => {
        this.info = res; // 存储上下文
        resolve(res);
      });
    return promise;
  }
  // 获取消息id，会关联上下文
  conversation({ msg, opts }) {
    return this.send({
      msg,
      opts: opts ?? {
        ...this.info,
      },
    });
  }
  // 清空上下文信息
  clearConversation() {
    this.info = null;
  }
}
